#!/usr/bin/python
import sys
from Crypto.PublicKey import RSA
from Crypto.Cipher import PKCS1_v1_5 as Cipher_pkcs1_v1_5
from Crypto.Signature import PKCS1_v1_5 as Signature_pkcs1_v1_5



def decrypt(source, private_key):
    cipher = Cipher_pkcs1_v1_5.new(RSA.importKey(private_key))
    input_len = len(source)
    offset = 0
    i = 0
    out = (bytes)(0)
    while input_len - offset > 0:
        if input_len - offset > 128:
            cache = cipher.decrypt(source[offset:offset+128], 'ERROR')
        else:
            cache = cipher.decrypt(source[offset:input_len], 'ERROR')
        i = i + 1
        offset = i * 128
        out += cache

    return out


def main():
    source_file = sys.argv[1]
    target_file = sys.argv[2]
    private_key_file = sys.argv[3]
    private_key = None

    with open(private_key_file) as file_obj:
        private_key = file_obj.read().replace("\\s", "").replace("---+[a-zA-Z]+---+", "")

    with open(sys.argv[1], "rb") as f:
        source = f.read()

    target = decrypt(source, private_key)

    with open(sys.argv[2], "wb") as f:
        f.write(target)

if __name__ == '__main__':
    main()

